package GUI.anim;

import java.awt.Graphics2D;

public class Animator {
	private Animation anim = null;
	private int frame = 0;
	private long lastTime = 0;
	private boolean running = false;
	private boolean dir = false;
	
	public Animator() { }
	
	public Animator(Animation ani)
	{
		setAnimation(ani);
	}
	
	public void setAnimation(Animation ani)
	{
		this.anim = ani;
		frame = 0;
		dir = false;
	}
	
	public Animation getAnimation()
	{
		return anim;
	}
	
	public void tick()
	{
		if(running)
		{
			long delta = System.currentTimeMillis() - lastTime;
			long elapsed = 0;
			while(delta > anim.frames[frame].delay)
			{
				delta -= anim.frames[frame].delay;
				elapsed += anim.frames[frame].delay;
				advance();
			}
			lastTime += elapsed;
		}
	}
	
	private void advance()
	{
		if(anim.swingMode)
		{
			if(dir)
			{
				frame--;
				if(frame < 0) { frame = 1; dir = false; }
			}
			else
			{
				frame++;
				if(frame >= anim.frameCount) { frame = anim.frameCount - 2; dir = true; }
			}
		}
		else
		{
			frame = (frame + 1) % anim.frameCount;
		}
	}
	
	public void play()
	{
		if(anim != null)
		{
			running = true;
			lastTime = System.currentTimeMillis();
		}
	}
	
	public void pause()
	{
		running = false;
	}
	
	public void stop()
	{
		running = false;
		frame = 0;
	}
	
	public void drawFrame(Graphics2D g, int x, int y)
	{
		if(anim == null) return;
		tick();
		anim.drawFrame(g, frame, x, y);
	}
	
	public int getFrame() {
		return frame;
	}
}
